from django.shortcuts import render, redirect
from django.http import HttpResponse
from django.contrib.auth import login
from .forms import RegisterForm

from .models import Post
import markdown
from .models import Post,Category,Tag

def index(request):
    posts=Post.objects.all()
    post_list = Post.objects.all().order_by('-createtime')
    return render(request, 'blog/index.html', context={'post_list': post_list})

    # data={
    #     'title': '我的博客首页',
    #     'welcome': '欢迎访问我的博客首页'
    # }
    # return render(request, 'blog/index.html', context=data)
    # return HttpResponse("欢迎访问我的博客首页！")

from django.shortcuts import render,get_object_or_404
def detail(request,pk):
    post = get_object_or_404(Post,pk=pk)
    #增加makdown支持
    post.body = markdown.markdown(post.body, extensions=[
                                    'markdown.extensions.extra',
                                    'markdown.extensions.codehilite',
                                    'markdown.extensions.toc'])

    return render(request,"blog/detail.html", context={'post':post})

#归档页面视图函数
def archive(request, year, month):
    #created_time.year 作为方法的参数，点号需要替换成2个下划线；
    post_list = Post.objects.filter(createtime__year=year,
                                    createtime__month=month
                                    ).order_by('-createtime')
    return render(request, 'blog/index.html', context={'post_list': post_list})



#分类页面功能实现
def category(request, pk):
    # 记得在开始部分导入 Category 类
    cate = get_object_or_404(Category, pk=pk)
    post_list = Post.objects.filter(category=cate).order_by('-createtime')
    return render(request, 'blog/index.html', context={'post_list': post_list})

#标签页面功能
def tag(request, pk):
    # 记得在开始部分导入 Tag 类
    t = get_object_or_404(Tag, pk=pk)
    post_list = Post.objects.filter(tag=t).order_by('-createtime')
    return render(request, 'blog/index.html', context={'post_list': post_list})

def register(request):
    if request.method == 'POST':
        form = RegisterForm(request.POST)
        if form.is_valid():
            user = form.save()
            login(request, user)
            return redirect('blog:index')  # 注册后直接跳转到首页
    else:
        form = RegisterForm()
    
    return render(request, 'blog/register.html', context={'form': form})
